﻿using Core.GameTool.Framework.Common;
using Core.GameTool.Framework.Extensions;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;

namespace Core.GameTool.Ocr
{
    public class PaddleOcr
    {
        #region DllImport

        [DllImport("ocr.dll", EntryPoint = "Test", CallingConvention = CallingConvention.Cdecl)]
        private extern static void Test();

        [DllImport("ocr.dll", EntryPoint = "LoadConfig", CallingConvention = CallingConvention.Cdecl)]
        private extern static int LoadConfig(string path);

        [DllImport("ocr.dll", EntryPoint = "Ocr", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        private extern static IntPtr Ocr(byte[] bts,int len,int width,int height,ref int outlen);

        [DllImport("ocr.dll", EntryPoint = "DeleteMemeoy", CallingConvention = CallingConvention.Cdecl)]
        private extern static void DeleteMemeoy(IntPtr ptr);

        #endregion

        public static int InitOcr()
        {
            return LoadConfig($@"{Environment.CurrentDirectory}\config.txt");
        }

        public static List<OcrInfo> Ocr(byte[] imgbts)
        {
            var img = ImgHelper.BtsToImage(imgbts);
            int outlen = 0;
            var ptr = Ocr(imgbts, imgbts.Length, img.Width, img.Height, ref outlen);
            var buffer = new byte[outlen];
            Marshal.Copy(ptr, buffer, 0, outlen);
            var json = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            LogText.WriteLog(json);
            return json.ToObject<List<OcrInfo>>();
        }
    }
}
